Ext.namespace("Microtraining.Admin.Subject");
Mt = Microtraining.Admin;
Mt.Subject={
	/**
	 * 全局配置
	 */
	Config:{
		/**
		 *分页:每页显示记录数
		 */
		PageSize:15,
		/**
		 *显示配置
		 */
		View:{
			/**
			 * 显示专场的视图相对专场列表Grid的位置
			 * 1:上方,2:下方,3:左侧,4:右侧,
			 */
			Direction:2,
			/**
			 *是否显示。
			 */
			IsShow:0,
			/**
			 * 是否固定显示专场信息页(或者打开新窗口)
			 */
			IsFix:0
		}
	},
	/**
	 * Cookie设置
	 */
	Cookie:new Ext.state.CookieProvider(),
	/**
	 * 初始化
	 */
	Init:function(){
		if (Mt.Subject.Cookie.get('View.Direction')){
			Mt.Subject.Config.View.Direction=Mt.Subject.Cookie.get('View.Direction');
		}
		if (Mt.Subject.Cookie.get('View.IsFix')!=null){
			Mt.Subject.Config.View.IsFix=Mt.Subject.Cookie.get('View.IsFix');
		}
	}
};
/**
 * Model:数据模型
 */
Mt.Subject.Store = {
	/**
	 * 专场
	 */
	subjectStore:new Ext.data.Store({
		reader: new Ext.data.JsonReader({
			totalProperty: 'totalCount',
			successProperty: 'success',
			root: 'data',remoteSort: true,
			fields : [
        {name: 'subject_id',type: 'int'},
        {name: 'company_id',type: 'int'},
        {name: 'company_name',type: 'string'},
        {name: 'admin_name',type: 'string'},
        {name: 'subject_name',type: 'string'},
        {name: 'isShow',type: 'string'},
        {name: 'sort_order',type: 'int'},
        {name: 'lessonStr',type: 'string'},
        {name: 'memberStr',type: 'string'},
        {name: 'head_image',type: 'string'},
        {name: 'begin_time',type: 'date',dateFormat:'Y-m-d H:i:s'},
        {name: 'end_time',type: 'date',dateFormat:'Y-m-d H:i:s'}
			]}
		),
		writer: new Ext.data.JsonWriter({
			encode: false
		}),
		listeners : {
			beforeload : function(store, options) {
				if (Ext.isReady) {
					if (!options.params.limit)options.params.limit=Mt.Subject.Config.PageSize;
					Ext.apply(options.params, Mt.Subject.View.Running.subjectGrid.filter);//保证分页也将查询条件带上
				}
			}
		}
	}),
  /**
   * 企业
   */
  companyStoreForCombo:new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url: 'home/admin/src/httpdata/company.php'
    }),
    reader: new Ext.data.JsonReader({
      root: 'companys',
      autoLoad: true,
      totalProperty: 'totalCount',
      idProperty: 'company_id'
    }, [
      {name: 'company_id', mapping: 'company_id'},
      {name: 'company_name', mapping: 'company_name'}
    ])
  }),
  /**
   * 专场课程
   */
  slessonStore:new Ext.data.Store({
    reader: new Ext.data.JsonReader({
      totalProperty: 'totalCount',
      successProperty: 'success',
      root: 'data',remoteSort: true,
      fields : [
        {name: 'slesson_id',type: 'int'},
        {name: 'subject_name',type: 'string'},
        {name: 'lesson_name',type: 'string'} 
      ]}
    ),
    writer: new Ext.data.JsonWriter({
      encode: false 
    }),
    listeners : {
      beforeload : function(store, options) {
        if (Ext.isReady) {
          if (!options.params.limit)options.params.limit=Mt.Subject.Config.PageSize;
          Ext.apply(options.params, Mt.Subject.View.Running.slessonGrid.filter);//保证分页也将查询条件带上
        }
      }
    }
  }),
  /**
   * 课程
   */
  selectLessonStore:new Ext.data.Store({
    reader: new Ext.data.JsonReader({
      totalProperty: 'totalCount',
      successProperty: 'success',
      root: 'data',remoteSort: true,
      fields : [
        {name: 'lesson_id',type: 'int'},
        {name: 'company_id',type: 'int'},
        {name: 'company_name',type: 'string'},
        {name: 'admin_name',type: 'string'},
        {name: 'lesson_name',type: 'string'},
        {name: 'keywords',type: 'string'} ,
        {name: 'sort_order',type: 'int'},
        {name: 'memberStr',type: 'string'}
      ]}
    ),
    writer: new Ext.data.JsonWriter({
      encode: false
    }),
    listeners : {
      beforeload : function(store, options) {
        if (Ext.isReady) {
          Ext.apply(options.params, Mt.Subject.View.Running.selectLessonWindow.lessonGrid.filter);//保证分页也将查询条件带上
        }
      },
      load : function(records,options){
        if (records&&records.data&&records.data.items) {
          var selData  = Mt.Subject.View.Running.selectLessonWindow.selData;//选中的课程
          var data     = records.data.items;
          //把已经推荐的课程选中
          var sm=Mt.Subject.View.Running.selectLessonWindow.lessonGrid.sm;
          var rows=Mt.Subject.View.Running.selectLessonWindow.lessonGrid.getView().getRows();
          for(var i=0;i<rows.length;i++){
            if(selData[data[i]['data'].lesson_id]){
              sm.selectRow(i, true);
            }
          }
        }
      }
    }
  }),
  /**
   * 企业
   */
  companyStoreForCombo:new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url: 'home/admin/src/httpdata/company.php'
    }),
    reader: new Ext.data.JsonReader({
      root: 'companys',
      autoLoad: true,
      totalProperty: 'totalCount',
      idProperty: 'company_id'
    }, [
      {name: 'company_id', mapping: 'company_id'},
      {name: 'company_name', mapping: 'company_name'}
    ])
  }),
  /**
   * 课程
   */
  lessonStoreForCombo:new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url: 'home/admin/src/httpdata/lesson.php'
    }),
    reader: new Ext.data.JsonReader({
      root: 'lessons',
      autoLoad: true,
      totalProperty: 'totalCount',
      idProperty: 'lesson_id'
    }, [
      {name: 'lesson_id', mapping: 'lesson_id'},
      {name: 'lesson_name', mapping: 'lesson_name'}
    ])
  }),
  /**
   * 会员
   */
  selectMemberStore:new Ext.data.Store({
    reader: new Ext.data.JsonReader({
      totalProperty: 'totalCount',
      successProperty: 'success',
      root: 'data',remoteSort: true,
      fields : [
        {name: 'member_id',type: 'int'},
        {name: 'company_id',type: 'int'},
        {name: 'company_name',type: 'string'},
        {name: 'department_id',type: 'int'},
        {name: 'department_name',type: 'string'},
        {name: 'position_id',type: 'int'},
        {name: 'position_name',type: 'string'},
        {name: 'area_id',type: 'int'},
        {name: 'area_name',type: 'string'},
        {name: 'username',type: 'string'},
        {name: 'password',type: 'string'},
        {name: 'realname',type: 'string'},
        {name: 'code',type: 'string'},
        {name: 'tel',type: 'string'},
        {name: 'email',type: 'string'},
        {name: 'qq',type: 'string'},
        {name: 'weixin',type: 'string'},
        {name: 'icon_image',type: 'string'},
        {name: 'point',type: 'float'}
      ]}
    ),
    writer: new Ext.data.JsonWriter({
      encode: false
    }),
    listeners : {
      beforeload : function(store, options) {
        if (Ext.isReady) {
          Ext.apply(options.params, Mt.Subject.View.Running.selectMemberWindow.memberGrid.filter);//保证分页也将查询条件带上
        }
      },
      load : function(records,options){
        if (records&&records.data&&records.data.items) {
          var selData  = Mt.Subject.View.Running.selectMemberWindow.selData;//选中的会员
          var data     = records.data.items;
          //把已经推荐的会员选中
          var sm=Mt.Subject.View.Running.selectMemberWindow.memberGrid.sm;
          var rows=Mt.Subject.View.Running.selectMemberWindow.memberGrid.getView().getRows();
          for(var i=0;i<rows.length;i++){
            if(selData[data[i]['data'].member_id]){
              sm.selectRow(i, true);
            }
          }
        }
      }
    }
  }),
  /**
   * 企业
   */
  companyStoreForCombo:new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url: 'home/admin/src/httpdata/company.php'
    }),
    reader: new Ext.data.JsonReader({
      root: 'companys',
      autoLoad: true,
      totalProperty: 'totalCount',
      idProperty: 'company_id'
    }, [
      {name: 'company_id', mapping: 'company_id'},
      {name: 'company_name', mapping: 'company_name'}
    ])
  }),
  /**
   * 部门
   */
  departmentStoreForCombo:new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url: 'home/admin/src/httpdata/department.php'
    }),
    reader: new Ext.data.JsonReader({
      root: 'departments',
      autoLoad: true,
      totalProperty: 'totalCount',
      idProperty: 'department_id'
    }, [
      {name: 'department_id', mapping: 'department_id'},
      {name: 'department_name', mapping: 'department_name'}
    ])
  }),
  /**
   * 职位
   */
  positionStoreForCombo:new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url: 'home/admin/src/httpdata/position.php'
    }),
    reader: new Ext.data.JsonReader({
      root: 'positions',
      autoLoad: true,
      totalProperty: 'totalCount',
      idProperty: 'position_id'
    }, [
      {name: 'position_id', mapping: 'position_id'},
      {name: 'position_name', mapping: 'position_name'}
    ])
  }),
  /**
   * 地区
   */
  areaStoreForCombo:new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url: 'home/admin/src/httpdata/area.php'
    }),
    reader: new Ext.data.JsonReader({
      root: 'areas',
      autoLoad: true,
      totalProperty: 'totalCount',
      idProperty: 'area_id'
    }, [
      {name: 'area_id', mapping: 'area_id'},
      {name: 'area_name', mapping: 'area_name'}
    ])
  })
};
/**
 * View:专场显示组件
 */
Mt.Subject.View={
	/**
	 * 编辑窗口：新建或者修改专场
	 */
	EditWindow:Ext.extend(Ext.Window,{
		constructor : function(config) {
			config = Ext.apply({
				/**
				 * 自定义类型:保存类型
				 * 0:保存窗口,1:修改窗口
				 */
				savetype:0,
				closeAction : "hide",
				constrainHeader:true,maximizable: true,collapsible: true,
				width : 450,height : 550,minWidth : 400,minHeight : 450,
				layout : 'fit',plain : true,buttonAlign : 'center',
				defaults : {
					autoScroll : true
				},
				listeners:{
					beforehide:function(){
						this.editForm.form.getEl().dom.reset();
					}
				},
				items : [
					new Ext.form.FormPanel({
						ref:'editForm',layout:'form',fileUpload: true,
						labelWidth : 100,labelAlign : "center",
						bodyStyle : 'padding:5px 5px 0',align : "center",
						api : {},
						defaults : {
							xtype : 'textfield',anchor:'98%'
						},
						items : [
        {xtype: 'hidden',name : 'subject_id',ref:'../subject_id'},
        /*{xtype: 'hidden',name : 'company_id',ref:'../company_id'},
        {
           fieldLabel : '所属企业',xtype: 'combo',name : 'company_name',ref : '../company_name',
           store:Mt.Subject.Store.companyStoreForCombo,emptyText: '请选择所属企业',itemSelector: 'div.search-item',
           loadingText: '查询中...',width: 570, pageSize:Mt.Subject.Config.PageSize,
           displayField:'company_name',grid:this,
           mode: 'remote',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
           forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
           tpl:new Ext.XTemplate(
             '<tpl for="."><div class="search-item">',
               '<h3>{company_name}</h3>',
             '</div></tpl>'
           ),
           listeners:{
             'beforequery': function(event){delete event.combo.lastQuery;}
           },
           onSelect:function(record,index){
             if(this.fireEvent('beforeselect', this, record, index) !== false){
              this.grid.company_id.setValue(record.data.company_id);
              this.grid.company_name.setValue(record.data.company_name);
              this.collapse();
             }
           }
        },*/
        {fieldLabel : '专场名称',name : 'subject_name'},
        {xtype: 'hidden',  name : 'head_image',ref:'../head_image'},
         {fieldLabel : '头像',name : 'head_imageUpload',ref:'../head_imageUpload',xtype:'fileuploadfield',
          emptyText: '请上传头像文件',buttonText: '',accept:'image/*',buttonCfg: {iconCls: 'upload-icon'}},
        {fieldLabel : '开始时间',name : 'begin_time',xtype : 'datefield',format : "Y-m-d"},
        {fieldLabel : '结束时间',name : 'end_time',xtype : 'datefield',format : "Y-m-d"},
        {fieldLabel : '排序',name : 'sort_order',xtype : 'numberfield'},
        {fieldLabel : '是否显示',hiddenName : 'isShow'
           ,xtype:'combo',ref:'../isShow',mode : 'local',triggerAction : 'all',
           lazyRender : true,editable: false,allowBlank : false,valueNotFoundText:'否',
           store : new Ext.data.SimpleStore({
             fields : ['value', 'text'],
             data : [['0', '否'], ['1', '是']]
           }),emptyText: '请选择是否显示',
           valueField : 'value',displayField : 'text'
        }
						]
					})
				],
				buttons : [{
					text: "",ref : "../saveBtn",scope:this,
					handler : function() {

						if (!this.editForm.getForm().isValid()) {
							return;
						}
						editWindow=this;
						if (this.savetype==0){
							this.editForm.api.submit=ExtServiceSubject.save;
							this.editForm.getForm().submit({
								success : function(form, action) {
									Ext.Msg.alert("提示", "保存成功！");
									Mt.Subject.View.Running.subjectGrid.doSelectSubject();
									form.reset();
									editWindow.hide();
								},
								failure : function(form, response) {
									Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
								}
							});
						}else{
							this.editForm.api.submit=ExtServiceSubject.update;
							this.editForm.getForm().submit({
								success : function(form, action) {
									Mt.Subject.View.Running.subjectGrid.store.reload();
									Ext.Msg.show({title:'提示',msg: '修改成功！',buttons: {yes: '确定'},fn: function(){
										Mt.Subject.View.Running.subjectGrid.bottomToolbar.doRefresh();
									}});
									form.reset();
									editWindow.hide();
								},
								failure : function(form, response) {
									Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
								}
							});
						}
					}
				}, {
					text : "取 消",scope:this,
					handler : function() {
						this.hide();
					}
				}, {
					text : "重 置",ref:'../resetBtn',scope:this,
					handler : function() {
						this.editForm.form.loadRecord(Mt.Subject.View.Running.subjectGrid.getSelectionModel().getSelected());
            this.head_imageUpload.setValue(this.head_image.getValue());
					}
				}]
			}, config);
			Mt.Subject.View.EditWindow.superclass.constructor.call(this, config);
		}
	}),
	/**
	 * 显示专场详情
	 */
	SubjectView:{
		/**
		 * Tab页：容器包含显示与专场所有相关的信息
		 */
		Tabs:Ext.extend(Ext.TabPanel,{
			constructor : function(config) {
				config = Ext.apply({
					region : 'south',collapseMode : 'mini',split : true,
					activeTab: 1, tabPosition:"bottom",resizeTabs : true,
					header:false,enableTabScroll : true,tabWidth:'auto', margins : '0 3 3 0',
					defaults : {
						autoScroll : true,
						layout:'fit'
					},
					listeners:{
						beforetabchange:function(tabs,newtab,currentTab){
							if (tabs.tabFix==newtab){
								if (Mt.Subject.View.Running.subjectGrid.getSelectionModel().getSelected()==null){
									Ext.Msg.alert('提示', '请先选择专场！');
									return false;
								}
								Mt.Subject.Config.View.IsShow=1;
								Mt.Subject.View.Running.subjectGrid.showSubject();
								Mt.Subject.View.Running.subjectGrid.tvpView.menu.mBind.setChecked(false);
								return false;
							}
						}
					},
					items: [
						{title:'+',tabTip:'取消固定',ref:'tabFix',iconCls:'icon-fix'}
					]
				}, config);
				Mt.Subject.View.SubjectView.Tabs.superclass.constructor.call(this, config);
        Mt.Subject.View.Running.slessonGrid=new Mt.Subject.View.SlessonView.Grid();
				this.onAddItems();
			},
			/**
			 * 根据布局调整Tabs的宽度或者高度以及折叠
			 */
			enableCollapse:function(){
				if ((Mt.Subject.Config.View.Direction==1)||(Mt.Subject.Config.View.Direction==2)){
					this.width =Ext.getBody().getViewSize().width;
					this.height=Ext.getBody().getViewSize().height/2;
				}else{
					this.width =Ext.getBody().getViewSize().width/2;
					this.height=Ext.getBody().getViewSize().height;
				}
				this.ownerCt.setSize(this.width,this.height);
				if (this.ownerCt.collapsed)this.ownerCt.expand();
				this.ownerCt.collapsed=false;
			},
			onAddItems:function(){
				this.add(
					{title: '基本信息',ref:'tabSubjectDetail',iconCls:'tabs',
					 tpl: [
						 '<table class="viewdoblock">',
             '  <tr class="entry"><td class="head">所属企业</td><td class="content">{company_name}</td></tr>',
             '  <tr class="entry"><td class="head">所属用户</td><td class="content">{admin_name}</td></tr>',
             '  <tr class="entry"><td class="head">专场名称</td><td class="content">{subject_name}</td></tr>',
             '  <tr class="entry"><td class="head">图标路径</td><td class="content">{head_image}</td></tr>',
             '  <tr class="entry"><td class="head">图标</td><td class="content"><tpl if="head_image"><a href="upload/images/{head_image}" target="_blank"><img width="50px" height="50px" src="upload/images/{head_image}" /></a></tpl></td></tr>',
						 '</table>'
					 ]}
				);
        /*this.add(
          {title: '专场课程',iconCls:'tabs',tabWidth:150,
           items:[Mt.Subject.View.Running.slessonGrid]
          }
        );*/
			}
		}),
		/**
		 * 窗口:显示专场信息
		 */
		Window:Ext.extend(Ext.Window,{
			constructor : function(config) {
				config = Ext.apply({
					title:"查看专场",constrainHeader:true,maximizable: true,minimizable : true,
					width : 705,height : 500,minWidth : 450,minHeight : 400,
					layout : 'fit',resizable:true,plain : true,bodyStyle : 'padding:5px;',
					closeAction : "hide",
					items:[new Mt.Subject.View.SubjectView.Tabs({ref:'winTabs',tabPosition:'top'})],
					listeners: {
						minimize:function(w){
							w.hide();
							Mt.Subject.Config.View.IsShow=0;
							Mt.Subject.View.Running.subjectGrid.tvpView.menu.mBind.setChecked(true);
						},
						hide:function(w){
							Mt.Subject.View.Running.subjectGrid.tvpView.toggle(false);
						}
					},
					buttons: [{
						text: '新增专场',scope:this,
						handler : function() {this.hide();Mt.Subject.View.Running.subjectGrid.addSubject();}
					},{
						text: '修改专场',scope:this,
						handler : function() {this.hide();Mt.Subject.View.Running.subjectGrid.updateSubject();}
					}]
				}, config);
				Mt.Subject.View.SubjectView.Window.superclass.constructor.call(this, config);
			}
		})
	},
  /**
   * 视图：课程
   */
  LessonView:{
    SelectLessonWindow:Ext.extend(Ext.Window,{
      constructor : function(config) {
        config = Ext.apply({
          selData:null,//选中的课程
          oldData:null,//已关联的课程
          title:"选择课程",updateData:null,closeAction:"hide",constrainHeader:true,maximizable:true,collapsible:true,
          width:720,minWidth:720,height:560,minHeight:450,layout:'fit',plain : true,buttonAlign : 'center',
          defaults : {autoScroll : true,},
          listeners:{
            beforehide:this.doHide
          },
          items : [new Mt.Subject.View.LessonView.LessonGrid({ref:"lessonGrid"})],
          buttons : [ {
            text: "确定",ref : "../saveBtn",scope:this,
            handler : function() {
              var selData = this.selData;
              var oldData = this.oldData;
              //专场标识
              var subject_id=Mt.Subject.View.Running.subjectGrid.getSelectionModel().getSelected().data.subject_id;
              var condition={'selData':selData,"oldData":oldData,"subject_id":subject_id};
              Ext.Msg.show({
                title: '请等待', msg: '操作进行中，请稍后...',
                animEl: 'loading', icon: Ext.Msg.WARNING,
                closable: true, progress: true, progressText: '', width: 300
              });
              ExtServiceSubject.updateSubjectLesson(condition,function(provider, response) {
                if (response.result.success==true) {
                  var msg = "操作成功！";
                  if(response.result.del){
                    msg += "<font color=red>取消</font>了<font color=red>"+response.result.del+"</font>门关联课程,";
                  }
                  if(response.result.add){
                    msg += "<font color=green>添加</font>了<font color=green>"+response.result.add+"</font>门关联课程";
                  }
                  Ext.Msg.alert('提示', msg);
                } else {
                  Mt.Subject.Store.selectLessonStore.removeAll();
                  Ext.Msg.alert('提示', response.result.msg);
                }
                Mt.Subject.View.Running.selectLessonWindow.hideWindow();
                Mt.Subject.View.Running.subjectGrid.doSelectSubject();
              });
            }
          }, {
            text : "取 消",scope:this,
            handler : function() {
              this.hide();
            }
          }]
        }, config);
        Mt.Subject.View.LessonView.SelectLessonWindow.superclass.constructor.call(this, config);
      },
      /**
      * 根据选择的课程,改变标题
      */
      changeTitle: function(){
        var title   = "选择 课程";
        var selData = this.selData;
        var count   = this.objElCount(selData);
        if(count){
          title += "（已经选择了<font color=green>"+count+"</font>件课程）";
        }else{
          title += "（尚未选择任何课程）";
        }
        this.setTitle(title);
      },
      /**
      * 判断自定义对象元素个数
      */
      objElCount: function(obj){
        var count = 0;
        for(var n in obj){count++}
        return count;
      },
      /**
       * 确认取消图片处理
       * con:选择窗口
       */
      doHide: function (con) {
        //window初始化时会调用,此时con为null
        if(con){
          Ext.MessageBox.show({
            title:'提示',msg:'确定要取消么?<br /><font color=red>(所做操作将不会保存!)</font>',buttons:Ext.MessageBox.YESNO,icon:Ext.MessageBox.QUESTION,
            params:{con:con},
            fn:function(btn,text,opt) {
              if(btn=='yes') {
                con.hideWindow();
              }
            }
          });
          return false;
        }
      },
      /**
       * 隐藏窗口
       */
      hideWindow: function () {
        //移除beforehide事件，为了防止hide时进入死循环
        this.un('beforehide',this.doHide);
        this.hide();
        this.addListener('beforehide',this.doHide);
      }
    }),
    LessonGrid:Ext.extend(Ext.grid.GridPanel,{
      constructor : function(config) {
        config = Ext.apply({
          /**
           * 查询条件
           */
          filter:null,subject_id:null,region : 'center',store : Mt.Subject.Store.selectLessonStore,sm : this.sm,
          trackMouseOver : true,enableColumnMove : true,columnLines : true,loadMask : true,stripeRows : true,headerAsText : false,
          loadMask : {msg : '加载数据中，请稍候...'},
          defaults : {autoScroll : true},
          cm : new Ext.grid.ColumnModel({
            defaults:{width:120,sortable : true},
            columns : [
              this.sm,
              {header : '标识',dataIndex : 'lesson_id',hidden:true},
              {header : '所属用户',dataIndex : 'admin_name'},
              {header : '课程名称',dataIndex : 'lesson_name'},
              // {header : '内容关键字',dataIndex : 'keywords'}, 
              {header : '排序',dataIndex : 'sort_order'}
            ]
          }),
          tbar : {
            xtype : 'container',layout : 'anchor',
            height : 27,style:'font-size:14px',
            defaults : {
              height : 27,anchor : '100%'
            },
            items : [
              new Ext.Toolbar({
                enableOverflow: true,width : 80,ref:'menus',
                defaults : {
                  xtype : 'textfield',
                  listeners : {
                     specialkey : function(field, e) {
                      if (e.getKey() == Ext.EventObject.ENTER)this.ownerCt.ownerCt.ownerCt.doSelectLesson();
                    }
                  }
                },
                items : [
                  {text: '全部',ref:'../../isSelect',xtype:'tbsplit',iconCls : 'icon-view',enableToggle: true,
                     toggleHandler:function(item, checked){
                      if (checked==true){
                        Mt.Subject.View.Running.selectLessonWindow.lessonGrid.topToolbar.menus.select.setChecked(true);
                      }else{
                        Mt.Subject.View.Running.selectLessonWindow.lessonGrid.topToolbar.menus.all.setChecked(true);
                      }
                    },
                    menu: {
                      items: [
                        {text: '全部',checked: true,group: 'isSelect',ref:'../../all',
                          checkHandler: function(item, checked){
                            if (checked){
                              Mt.Subject.View.Running.selectLessonWindow.lessonGrid.isSelect.setText(item.text);
                              Mt.Subject.View.Running.selectLessonWindow.lessonGrid.filter.selectType=0;
                            }
                            Mt.Subject.View.Running.selectLessonWindow.lessonGrid.doSelectLesson();
                          }
                        },
                        {text: '未选择',checked: false,group: 'isSelect',ref:'../../unselect',
                            checkHandler: function(item, checked){
                              if (checked){
                                Mt.Subject.View.Running.selectLessonWindow.lessonGrid.isSelect.setText(item.text);
                                Mt.Subject.View.Running.selectLessonWindow.lessonGrid.filter.selectType=2;
                              }
                              Mt.Subject.View.Running.selectLessonWindow.lessonGrid.doSelectLesson();
                            }
                        },
                        {text: '已选择',checked: false,group: 'isSelect',ref:'../../select',
                            checkHandler: function(item, checked){
                              if (checked){
                                Mt.Subject.View.Running.selectLessonWindow.lessonGrid.isSelect.setText(item.text);
                                Mt.Subject.View.Running.selectLessonWindow.lessonGrid.filter.selectType=1;
                              }
                              Mt.Subject.View.Running.selectLessonWindow.lessonGrid.doSelectLesson();
                          }
                        }
                       ]
                    }
                  },
                  '课程名称','&nbsp;&nbsp;',{ref: '../llesson_name'},'&nbsp;&nbsp;',
                  {
                    xtype : 'button',text : '查询',scope: this,
                    handler : function() {
                      this.doSelectLesson();
                    }
                  },
                  {
                    xtype : 'button',text : '重置',scope: this,
                    handler : function() {
                      this.topToolbar.llesson_name.setValue("");
                      this.filter={};
                      this.doSelectLesson();
                    }
                  }
                ]
              })
            ]
          },
          bbar: new Ext.PagingToolbar({
            pageSize: Mt.Subject.Config.PageSize,
            store: Mt.Subject.Store.selectLessonStore,
            scope:this,autoShow:true,displayInfo: true,
            displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',
            emptyMsg: "无显示数据",
            items: [
              {xtype:'label', text: '每页显示'},
              {xtype:'numberfield', value:Mt.Subject.Config.PageSize,minValue:1,width:35,
                style:'text-align:center',allowBlank:false,
                listeners:
                {
                  change:function(Field, newValue, oldValue){
                    var num = parseInt(newValue);
                    if (isNaN(num) || !num || num<1)
                    {
                      num = Mt.Subject.Config.PageSize;
                      Field.setValue(num);
                    }
                    Mt.Subject.Config.PageSize = num;
                    this.ownerCt.ownerCt.doSelectLesson();
                  },
                  specialKey :function(field,e){
                    if (e.getKey() == Ext.EventObject.ENTER){
                      var num = parseInt(field.getValue());
                      if (isNaN(num) || !num || num<1)
                      {
                        num = Mt.Subject.Config.PageSize;
                      }
                      Mt.Subject.Config.PageSize = num;
                      this.ownerCt.ownerCt.doSelectLesson();
                    }
                  }
                }
              },
              {xtype:'label', text: '个'}
            ]
          })
        }, config);
        //初始化显示课程列表
        //this.doSelectLesson();
        Mt.Subject.Store.selectLessonStore.proxy=new Ext.data.DirectProxy({
          api: {read:ExtServiceSubject.queryPageSubjectLesson}
        });
        Mt.Subject.View.LessonView.LessonGrid.superclass.constructor.call(this, config);
      },
      /**
      * SelectionModel
      */
      sm : new Ext.grid.CheckboxSelectionModel({
        listeners : {
          selectionchange:function(sm) {
            Mt.Subject.View.Running.selectLessonWindow.changeTitle();
            Mt.Subject.View.Running.selectLessonWindow.lessonGrid.changeFilter();
          },
          rowselect: function(sm, rowIndex, record) {
            var selLessonWin  = Mt.Subject.View.Running.selectLessonWindow;
            var selData    = selLessonWin.selData;
            var oldData    = selLessonWin.oldData;
            var lesson_id   = record.data.lesson_id;
            //添加该货品ID
            selData[lesson_id] = true;
            //判断是否是已关联的货品
            if(oldData[lesson_id]){
              oldData[lesson_id].active = true;
            }
          },
          rowdeselect: function(sm, rowIndex, record) {
            var selLessonWin  = Mt.Subject.View.Running.selectLessonWindow;
            var selData    = selLessonWin.selData;
            var oldData    = selLessonWin.oldData;
            var lesson_id   = record.data.lesson_id;
            //删除该货品ID
            delete selData[lesson_id];
            //判断是否是已关联的货品
            if(oldData[lesson_id]){
              oldData[lesson_id].active = false;
            }
          }
        }
      }),
      doSelectLesson : function() {
        var tmp_selLesson=this.filter.selLesson;
        if (this.topToolbar){
          var subject_id=this.subject_id;
          if (!this.filter.selectType)this.filter.selectType=0;
          var llesson_name = this.topToolbar.llesson_name.getValue();
          this.filter     ={'lesson_name':llesson_name,'subject_id':subject_id,'selectType':this.filter.selectType};
        }
        this.filter.selLesson=tmp_selLesson;
        var condition = {'start':0,'limit':Mt.Subject.Config.PageSize};
        Ext.apply(condition,this.filter);
        ExtServiceSubject.queryPageSubjectLesson(condition,function(provider, response) {
          if (response.result&&response.result.data) {
            var result       = new Array();
            result['data']     =response.result.data;
            result['totalCount'] =response.result.totalCount;
            Mt.Subject.Store.selectLessonStore.loadData(result);
          } else {
            Mt.Subject.Store.selectLessonStore.removeAll();
            Ext.Msg.alert('提示', '无符合条件的课程！');
          }
        });
      },
      /**
      * 修改查询条件
      */
      changeFilter: function(){
        var selData =Mt.Subject.View.Running.selectLessonWindow.selData;
        var selArr  = new Array();
        for(var x in selData){
          selArr.push(x);
        }
        this.filter.selLesson = selArr.join(",");
      }
    }),
  },
	/**
	 * 视图：专场课程列表
	 */
	SlessonView:{
		/**
		 *  当前创建的专场课程编辑窗口
		 */
		edit_window:null,
		/**
		 * 编辑窗口：新建或者修改专场课程
		 */
		EditWindow:Ext.extend(Ext.Window,{
			constructor : function(config) {
				config = Ext.apply({
					/**
					 * 自定义类型:保存类型
					 * 0:保存窗口,1:修改窗口
					 */
					savetype:0,closeAction : "hide",constrainHeader:true,maximizable: true,collapsible: true,
					width : 450,height : 550,minWidth : 400,minHeight : 450,
					layout : 'fit',plain : true,buttonAlign : 'center',
					defaults : {autoScroll : true},
					listeners:{
						beforehide:function(){
							this.editForm.form.getEl().dom.reset();
						}
					},
					items : [
						new Ext.form.FormPanel({
							ref:'editForm',layout:'form',fileUpload: true,
							labelWidth : 100,labelAlign : "center",
							bodyStyle : 'padding:5px 5px 0',align : "center",
							api : {},
							defaults : {
								xtype : 'textfield',anchor:'98%'
							},
							items : [
                {xtype: 'hidden',name : 'slesson_id',ref:'../slesson_id'},
                {xtype: 'hidden',name : 'subject_id',ref:'../subject_id'},
                {xtype: 'hidden',name : 'lesson_id',ref:'../lesson_id'},
                {
                   fieldLabel : '课程',xtype: 'combo',name : 'lesson_name',ref : '../lesson_name',
                   store:Mt.Subject.Store.lessonStoreForCombo,emptyText: '请选择课程',itemSelector: 'div.search-item',
                   loadingText: '查询中...',width: 570, pageSize:Mt.Subject.Config.PageSize,
                   displayField:'lesson_name',grid:this,
                   mode: 'remote',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                   forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
                   tpl:new Ext.XTemplate(
                     '<tpl for="."><div class="search-item">',
                       '<h3>{lesson_name}</h3>',
                     '</div></tpl>'
                   ),
                   listeners:{
                     'beforequery': function(event){delete event.combo.lastQuery;}
                   },
                   onSelect:function(record,index){
                     if(this.fireEvent('beforeselect', this, record, index) !== false){
                      this.grid.lesson_id.setValue(record.data.lesson_id);
                      this.grid.lesson_name.setValue(record.data.lesson_name);
                      this.collapse();
                     }
                   }
                }
                
							]
						})
					],
					buttons : [{
						text: "",ref : "../saveBtn",scope:this,
						handler : function() {

							if (!this.editForm.getForm().isValid()) {
								return;
							}
							editWindow=this;
							if (this.savetype==0){
								this.editForm.api.submit=ExtServiceSlesson.save;
								this.editForm.getForm().submit({
									success : function(form, action) {
										Ext.Msg.alert("提示", "保存成功！");
										Mt.Subject.View.Running.slessonGrid.doSelectSlesson();
										form.reset();
										editWindow.hide();
									},
									failure : function(form, response) {
										Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
									}
								});
							}else{
								this.editForm.api.submit=ExtServiceSlesson.update;
								this.editForm.getForm().submit({
									success : function(form, action) {
										Ext.Msg.show({title:'提示',msg: '修改成功！',buttons: {yes: '确定'},fn: function(){
											Mt.Subject.View.Running.slessonGrid.bottomToolbar.doRefresh();
										}});
										form.reset();
										editWindow.hide();
									},
									failure : function(form, response) {
										Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
									}
								});
							}
						}
					}, {
						text : "取 消",scope:this,
						handler : function() {
							this.hide();
						}
					}, {
						text : "重 置",ref:'../resetBtn',scope:this,
						handler : function() {
							this.editForm.form.loadRecord(Mt.Subject.View.Running.slessonGrid.getSelectionModel().getSelected());

						}
					}]
				}, config);
				Mt.Subject.View.SlessonView.EditWindow.superclass.constructor.call(this, config);
			}
		}),
		/**
		 * 查询条件
		 */
		filter:null,
		/**
		 * 视图：专场课程列表
		 */
		Grid:Ext.extend(Ext.grid.GridPanel, {
			constructor : function(config) {
				config = Ext.apply({
					store : Mt.Subject.Store.slessonStore,sm : this.sm,
					frame : true,trackMouseOver : true,enableColumnMove : true,columnLines : true,
					loadMask : true,stripeRows : true,headerAsText : false,
					defaults : {autoScroll : true},
					cm : new Ext.grid.ColumnModel({
						defaults:{
							width:120,sortable : true
						},
						columns : [
              this.sm,
              {header : '标识',dataIndex : 'slesson_id',hidden:true},
              {header : '课程',dataIndex : 'lesson_name'}
						]
					}),
					tbar : {
						xtype : 'container',layout : 'anchor',
						height : 27,style:'font-size:14px',
						defaults : {
							height : 27,anchor : '100%'
						},
						items : [
							new Ext.Toolbar({
								defaults:{
								  scope: this
								},
								items : [
									{
										text: '反选',iconCls : 'icon-reverse',
										handler: function(){
											this.onReverseSelect();
										}
									},'-',{
										text : '添加专场课程',iconCls : 'icon-add',
										handler : function() {
											this.addSlesson();
										}
									},'-',{
										text : '修改专场课程',ref: '../../btnUpdate',iconCls : 'icon-edit',disabled : true,
										handler : function() {
											this.updateSlesson();
										}
									},'-',{
										text : '删除专场课程', ref: '../../btnRemove',iconCls : 'icon-delete',disabled : true,
										handler : function() {
											this.deleteSlesson();
										}
									},'-']}
						)]
					},
					bbar: new Ext.PagingToolbar({
						pageSize: Mt.Subject.Config.PageSize,
						store: Mt.Subject.Store.slessonStore,scope:this,autoShow:true,displayInfo: true,
						displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',emptyMsg: "无显示数据",
						items: [
							{xtype:'label', text: '每页显示'},
							{xtype:'numberfield', value:Mt.Subject.Config.PageSize,minValue:1,width:35,style:'text-align:center',allowBlank: false,
								listeners:
								{
									change:function(Field, newValue, oldValue){
										var num = parseInt(newValue);
										if (isNaN(num) || !num || num<1)
										{
											num = Mt.Subject.Config.PageSize;
											Field.setValue(num);
										}
										this.ownerCt.pageSize= num;
										Mt.Subject.Config.PageSize = num;
										this.ownerCt.ownerCt.doSelectSlesson();
									},
									specialKey :function(field,e){
										if (e.getKey() == Ext.EventObject.ENTER){
											var num = parseInt(field.getValue());
											if (isNaN(num) || !num || num<1)num = Mt.Subject.Config.PageSize;
											this.ownerCt.pageSize= num;
											Mt.Subject.Config.PageSize = num;
											this.ownerCt.ownerCt.doSelectSlesson();
										}
									}
								}
							},{xtype:'label', text: '个'}
						]
					})
				}, config);
				/**
				 * 专场课程数据模型获取数据Direct调用
				 */
				Mt.Subject.Store.slessonStore.proxy=new Ext.data.DirectProxy({
					api: {read:ExtServiceSlesson.queryPageSlesson}
				});
				Mt.Subject.View.SlessonView.Grid.superclass.constructor.call(this, config);
			},
			/**
			 * 行选择器
			 */
			sm : new Ext.grid.CheckboxSelectionModel({
				listeners : {
					selectionchange:function(sm) {
						// 判断删除和更新按钮是否可以激活
						this.grid.btnRemove.setDisabled(sm.getCount() < 1);
						this.grid.btnUpdate.setDisabled(sm.getCount() != 1);
					}
				}
			}),
			/**
			 * 查询符合条件的专场课程
			 */
			doSelectSlesson : function() {
				if (Mt.Subject.View.Running.subjectGrid&&Mt.Subject.View.Running.subjectGrid.getSelectionModel().getSelected()){
					var subject_id = Mt.Subject.View.Running.subjectGrid.getSelectionModel().getSelected().data.subject_id;
					var condition = {'subject_id':subject_id,'start':0,'limit':Mt.Subject.Config.PageSize};
					this.filter     ={'subject_id':subject_id};
					ExtServiceSlesson.queryPageSlesson(condition,function(provider, response) {
						if (response.result){
							if (response.result.data) {
								var result       = new Array();
								result['data']     =response.result.data;
								result['totalCount'] =response.result.totalCount;
								Mt.Subject.Store.slessonStore.loadData(result);
							} else {
								Mt.Subject.Store.slessonStore.removeAll();
								Ext.Msg.alert('提示', '无符合条件的专场课程！');
							}

							if (Mt.Subject.Store.slessonStore.getTotalCount()>Mt.Subject.Config.PageSize){
								 Mt.Subject.View.Running.slessonGrid.bottomToolbar.show();
							}else{
								 Mt.Subject.View.Running.slessonGrid.bottomToolbar.hide();
							}
							Mt.Subject.View.Running.subjectGrid.ownerCt.doLayout();
						}
					});
				}
			},
			/**
			 * 反选
			 */
			onReverseSelect:function() {
				for (var i = this.getView().getRows().length - 1; i >= 0; i--) {
					if (this.sm.isSelected(i)) {
						this.sm.deselectRow(i);
					}else {
						this.sm.selectRow(i, true);
					}
				}
			},
			/**
			 * 新建专场课程
			 */
			addSlesson : function(){
				if (Mt.Subject.View.SlessonView.edit_window==null){
					Mt.Subject.View.SlessonView.edit_window=new Mt.Subject.View.SlessonView.EditWindow();
				}
				Mt.Subject.View.SlessonView.edit_window.resetBtn.setVisible(false);
				Mt.Subject.View.SlessonView.edit_window.saveBtn.setText('保 存');
				Mt.Subject.View.SlessonView.edit_window.setTitle('添加专场课程');
				Mt.Subject.View.SlessonView.edit_window.savetype=0;
				Mt.Subject.View.SlessonView.edit_window.slesson_id.setValue("");
				var company_id = Mt.Subject.View.Running.subjectGrid.getSelectionModel().getSelected().data.subject_id;
				Mt.Subject.View.SlessonView.edit_window.subject_id.setValue(company_id);

				Mt.Subject.View.SlessonView.edit_window.show();
				Mt.Subject.View.SlessonView.edit_window.maximize();
			},
			/**
			 * 编辑专场课程时先获得选中的专场课程信息
			 */
			updateSlesson : function() {
				if (Mt.Subject.View.SlessonView.edit_window==null){
					Mt.Subject.View.SlessonView.edit_window=new Mt.Subject.View.SlessonView.EditWindow();
				}
				Mt.Subject.View.SlessonView.edit_window.saveBtn.setText('修 改');
				Mt.Subject.View.SlessonView.edit_window.resetBtn.setVisible(true);
				Mt.Subject.View.SlessonView.edit_window.setTitle('修改专场课程');
				Mt.Subject.View.SlessonView.edit_window.editForm.form.loadRecord(this.getSelectionModel().getSelected());
				Mt.Subject.View.SlessonView.edit_window.savetype=1;

				Mt.Subject.View.SlessonView.edit_window.show();
				Mt.Subject.View.SlessonView.edit_window.maximize();
			},
			/**
			 * 删除专场课程
			 */
			deleteSlesson : function() {
				Ext.Msg.confirm('提示', '确实要删除所选的专场课程吗?', this.confirmDeleteSlesson,this);
			},
			/**
			 * 确认删除专场课程
			 */
			confirmDeleteSlesson : function(btn) {
				if (btn == 'yes') {
					var del_slesson_ids ="";
					var selectedRows  = this.getSelectionModel().getSelections();
					for ( var flag = 0; flag < selectedRows.length; flag++) {
						del_slesson_ids=del_slesson_ids+selectedRows[flag].data.slesson_id+",";
					}
					ExtServiceSlesson.deleteByIds(del_slesson_ids);
					this.doSelectSlesson();
					Ext.Msg.alert("提示", "删除成功！");
				}
			}
		})
	},
  /**
   * 视图：会员
   */
  MemberView:{
    SelectMemberWindow:Ext.extend(Ext.Window,{
      constructor : function(config) {
        config = Ext.apply({
          selData:null,//选中的会员
          oldData:null,//已关联的会员
          title:"选择会员",updateData:null,closeAction:"hide",constrainHeader:true,maximizable:true,collapsible:true,
          width:720,minWidth:720,height:560,minHeight:450,layout:'fit',plain : true,buttonAlign : 'center',
          defaults : {autoScroll : true,},
          listeners:{
            beforehide:this.doHide
          },
          items : [new Mt.Subject.View.MemberView.MemberGrid({ref:"memberGrid"})],
          buttons : [ {
            text: "确定",ref : "../saveBtn",scope:this,
            handler : function() {
              var selData = this.selData;
              var oldData = this.oldData;
              //专场标识
              var subject_id=Mt.Subject.View.Running.subjectGrid.getSelectionModel().getSelected().data.subject_id;
              var condition={'selData':selData,"oldData":oldData,"subject_id":subject_id};
              Ext.Msg.show({
                title: '请等待', msg: '操作进行中，请稍后...',
                animEl: 'loading', icon: Ext.Msg.WARNING,
                closable: true, progress: true, progressText: '', width: 300
              });
              ExtServiceSubject.updateSubjectMember(condition,function(provider, response) {
                if (response.result.success==true) {
                  var msg = "操作成功！";
                  if(response.result.del){
                    msg += "<font color=red>取消</font>了<font color=red>"+response.result.del+"</font>个关联会员,";
                  }
                  if(response.result.add){
                    msg += "<font color=green>添加</font>了<font color=green>"+response.result.add+"</font>个关联会员";
                  }
                  Ext.Msg.alert('提示', msg);
                } else {
                  Mt.Subject.Store.selectMemberStore.removeAll();
                  Ext.Msg.alert('提示', response.result.msg);
                }
                Mt.Subject.View.Running.selectMemberWindow.hideWindow();
                Mt.Subject.View.Running.subjectGrid.doSelectSubject();
              });
            }
          }, {
            text : "取 消",scope:this,
            handler : function() {
              this.hide();
            }
          }]
        }, config);
        Mt.Subject.View.MemberView.SelectMemberWindow.superclass.constructor.call(this, config);
      },
      /**
      * 根据选择的会员,改变标题
      */
      changeTitle: function(){
        var title   = "选择 会员";
        var selData = this.selData;
        var count   = this.objElCount(selData);
        if(count){
          title += "（已经选择了<font color=green>"+count+"</font>件会员）";
        }else{
          title += "（尚未选择任何会员）";
        }
        this.setTitle(title);
      },
      /**
      * 判断自定义对象元素个数
      */
      objElCount: function(obj){
        var count = 0;
        for(var n in obj){count++}
        return count;
      },
      /**
       * 确认取消图片处理
       * con:选择窗口
       */
      doHide: function (con) {
        //window初始化时会调用,此时con为null
        if(con){
          Ext.MessageBox.show({
            title:'提示',msg:'确定要取消么?<br /><font color=red>(所做操作将不会保存!)</font>',buttons:Ext.MessageBox.YESNO,icon:Ext.MessageBox.QUESTION,
            params:{con:con},
            fn:function(btn,text,opt) {
              if(btn=='yes') {
                con.hideWindow();
              }
            }
          });
          return false;
        }
      },
      /**
       * 隐藏窗口
       */
      hideWindow: function () {
        //移除beforehide事件，为了防止hide时进入死循环
        this.un('beforehide',this.doHide);
        this.hide();
        this.addListener('beforehide',this.doHide);
      }
    }),
    MemberGrid:Ext.extend(Ext.grid.GridPanel,{
      constructor : function(config) {
        config = Ext.apply({
          /**
           * 查询条件
           */
          filter:null,subject_id:null,region : 'center',store : Mt.Subject.Store.selectMemberStore,sm : this.sm,
          trackMouseOver : true,enableColumnMove : true,columnLines : true,loadMask : true,stripeRows : true,headerAsText : false,
          loadMask : {msg : '加载数据中，请稍候...'},
          defaults : {autoScroll : true},
          cm : new Ext.grid.ColumnModel({
            defaults:{width:120,sortable : true},
            columns : [
              this.sm,
              {header : '标识',dataIndex : 'member_id',hidden:true},
              {header : '用户名',dataIndex : 'username'},
              {header : '姓名',dataIndex : 'realname'},
              {header : '员工号',dataIndex : 'code'},
              // {header : '公司',dataIndex : 'company_name'},
              {header : '部门',dataIndex : 'department_name'},
              {header : '职位',dataIndex : 'position_name'},
              {header : '地区',dataIndex : 'area_name'}
            ]
          }),
          tbar : {
            xtype : 'container',layout : 'anchor',
            height : 27,style:'font-size:14px',
            defaults : {
              height : 27,anchor : '100%'
            },
            items : [
              new Ext.Toolbar({
                enableOverflow: true,width : 80,ref:'menus',
                defaults : {
                  xtype : 'textfield',
                  listeners : {
                     specialkey : function(field, e) {
                      if (e.getKey() == Ext.EventObject.ENTER)this.ownerCt.ownerCt.ownerCt.doSelectMember();
                    }
                  }
                },
                items : [
                  {text: '全部',ref:'../../isSelect',xtype:'tbsplit',iconCls : 'icon-view',enableToggle: true,
                     toggleHandler:function(item, checked){
                      if (checked==true){
                        Mt.Subject.View.Running.selectMemberWindow.memberGrid.topToolbar.menus.select.setChecked(true);
                      }else{
                        Mt.Subject.View.Running.selectMemberWindow.memberGrid.topToolbar.menus.all.setChecked(true);
                      }
                    },
                    menu: {
                      items: [
                        {text: '全部',checked: true,group: 'isSelect',ref:'../../all',
                          checkHandler: function(item, checked){
                            if (checked){
                              Mt.Subject.View.Running.selectMemberWindow.memberGrid.isSelect.setText(item.text);
                              Mt.Subject.View.Running.selectMemberWindow.memberGrid.filter.selectType=0;
                            }
                            Mt.Subject.View.Running.selectMemberWindow.memberGrid.doSelectMember();
                          }
                        },
                        {text: '未选择',checked: false,group: 'isSelect',ref:'../../unselect',
                            checkHandler: function(item, checked){
                              if (checked){
                                Mt.Subject.View.Running.selectMemberWindow.memberGrid.isSelect.setText(item.text);
                                Mt.Subject.View.Running.selectMemberWindow.memberGrid.filter.selectType=2;
                              }
                              Mt.Subject.View.Running.selectMemberWindow.memberGrid.doSelectMember();
                            }
                        },
                        {text: '已选择',checked: false,group: 'isSelect',ref:'../../select',
                            checkHandler: function(item, checked){
                              if (checked){
                                Mt.Subject.View.Running.selectMemberWindow.memberGrid.isSelect.setText(item.text);
                                Mt.Subject.View.Running.selectMemberWindow.memberGrid.filter.selectType=1;
                              }
                              Mt.Subject.View.Running.selectMemberWindow.memberGrid.doSelectMember();
                          }
                        }
                       ]
                    }
                  },
                  /*'公司','&nbsp;&nbsp;',{ref: '../mcompany_id',xtype: 'combo',
                     store:Mt.Subject.Store.companyStoreForCombo,hiddenName : 'company_id',
                     emptyText: '请选择公司',itemSelector: 'div.search-item',
                     loadingText: '查询中...',width:280,pageSize:Mt.Subject.Config.PageSize,
                     displayField:'company_name',valueField:'company_id',
                     mode: 'remote',editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                     forceSelection: true,triggerAction: 'all',resizable:true,selectOnFocus:true,
                     tpl:new Ext.XTemplate(
                       '<tpl for="."><div class="search-item">',
                       '<h3>{company_name}</h3>',
                       '</div></tpl>'
                     )
                  },'&nbsp;&nbsp;',*/
                  '部门','&nbsp;&nbsp;',{ref: '../mdepartment_id',xtype: 'combo',
                     store:Mt.Subject.Store.departmentStoreForCombo,hiddenName : 'department_id',
                     emptyText: '请选择部门',itemSelector: 'div.search-item',
                     loadingText: '查询中...',width:100,pageSize:Mt.Subject.Config.PageSize,
                     displayField:'department_name',valueField:'department_id',
                     mode: 'remote',editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                     forceSelection: true,triggerAction: 'all',resizable:true,selectOnFocus:true,
                     tpl:new Ext.XTemplate(
                       '<tpl for="."><div class="search-item">',
                       '<h3>{department_name}</h3>',
                       '</div></tpl>'
                     )
                  },'&nbsp;&nbsp;',
                  '职位','&nbsp;&nbsp;',{ref: '../mposition_id',xtype: 'combo',
                     store:Mt.Subject.Store.positionStoreForCombo,hiddenName : 'position_id',
                     emptyText: '请选择职位',itemSelector: 'div.search-item',
                     loadingText: '查询中...',width:100,pageSize:Mt.Subject.Config.PageSize,
                     displayField:'position_name',valueField:'position_id',
                     mode: 'remote',editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                     forceSelection: true,triggerAction: 'all',resizable:true,selectOnFocus:true,
                     tpl:new Ext.XTemplate(
                       '<tpl for="."><div class="search-item">',
                       '<h3>{position_name}</h3>',
                       '</div></tpl>'
                     )
                  },'&nbsp;&nbsp;',
                  '地区','&nbsp;&nbsp;',{ref: '../marea_id',xtype: 'combo',
                     store:Mt.Subject.Store.areaStoreForCombo,hiddenName : 'area_id',
                     emptyText: '请选择地区',itemSelector: 'div.search-item',
                     loadingText: '查询中...',width:100,pageSize:Mt.Subject.Config.PageSize,
                     displayField:'area_name',valueField:'area_id',
                     mode: 'remote',editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                     forceSelection: true,triggerAction: 'all',resizable:true,selectOnFocus:true,
                     tpl:new Ext.XTemplate(
                       '<tpl for="."><div class="search-item">',
                       '<h3>{area_name}</h3>',
                       '</div></tpl>'
                     )
                  },'&nbsp;&nbsp;',
                  '用户名','&nbsp;&nbsp;',{ref: '../musername',width:100},'&nbsp;&nbsp;',
                  {
                    xtype : 'button',text : '查询',scope: this,
                    handler : function() {
                      this.doSelectMember();
                    }
                  },
                  {
                    xtype : 'button',text : '重置',scope: this,
                    handler : function() {
                      // this.topToolbar.mcompany_id.setValue("");
                      this.topToolbar.mdepartment_id.setValue("");
                      this.topToolbar.mposition_id.setValue("");
                      this.topToolbar.marea_id.setValue("");
                      this.topToolbar.musername.setValue("");
                      this.filter={};
                      this.doSelectMember();
                    }
                  }
                ]
              })
            ]
          },
          bbar: new Ext.PagingToolbar({
            pageSize: Mt.Subject.Config.PageSize,
            store: Mt.Subject.Store.selectMemberStore,
            scope:this,autoShow:true,displayInfo: true,
            displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',
            emptyMsg: "无显示数据",
            items: [
              {xtype:'label', text: '每页显示'},
              {xtype:'numberfield', value:Mt.Subject.Config.PageSize,minValue:1,width:35,
                style:'text-align:center',allowBlank:false,
                listeners:
                {
                  change:function(Field, newValue, oldValue){
                    var num = parseInt(newValue);
                    if (isNaN(num) || !num || num<1)
                    {
                      num = Mt.Subject.Config.PageSize;
                      Field.setValue(num);
                    }
                    Mt.Subject.Config.PageSize = num;
                    this.ownerCt.ownerCt.doSelectMember();
                  },
                  specialKey :function(field,e){
                    if (e.getKey() == Ext.EventObject.ENTER){
                      var num = parseInt(field.getValue());
                      if (isNaN(num) || !num || num<1)
                      {
                        num = Mt.Subject.Config.PageSize;
                      }
                      Mt.Subject.Config.PageSize = num;
                      this.ownerCt.ownerCt.doSelectMember();
                    }
                  }
                }
              },
              {xtype:'label', text: '个'}
            ]
          })
        }, config);
        //初始化显示会员列表
        //this.doSelectMember();
        Mt.Subject.Store.selectMemberStore.proxy=new Ext.data.DirectProxy({
          api: {read:ExtServiceSubject.queryPageSubjectMember}
        });
        Mt.Subject.View.MemberView.MemberGrid.superclass.constructor.call(this, config);
      },
      /**
      * SelectionModel
      */
      sm : new Ext.grid.CheckboxSelectionModel({
        listeners : {
          selectionchange:function(sm) {
            Mt.Subject.View.Running.selectMemberWindow.changeTitle();
            Mt.Subject.View.Running.selectMemberWindow.memberGrid.changeFilter();
          },
          rowselect: function(sm, rowIndex, record) {
            var selMemberWin  = Mt.Subject.View.Running.selectMemberWindow;
            var selData    = selMemberWin.selData;
            var oldData    = selMemberWin.oldData;
            var member_id   = record.data.member_id;
            //添加该货品ID
            selData[member_id] = true;
            //判断是否是已关联的货品
            if(oldData[member_id]){
              oldData[member_id].active = true;
            }
          },
          rowdeselect: function(sm, rowIndex, record) {
            var selMemberWin  = Mt.Subject.View.Running.selectMemberWindow;
            var selData    = selMemberWin.selData;
            var oldData    = selMemberWin.oldData;
            var member_id   = record.data.member_id;
            //删除该货品ID
            delete selData[member_id];
            //判断是否是已关联的货品
            if(oldData[member_id]){
              oldData[member_id].active = false;
            }
          }
        }
      }),
      doSelectMember : function() {
        var tmp_selMember=this.filter.selMember;
        if (this.topToolbar){
          var subject_id=this.subject_id;
          if (!this.filter.selectType)this.filter.selectType=0;
          // var mcompany_id = this.topToolbar.mcompany_id.getValue();
          var mdepartment_id = this.topToolbar.mdepartment_id.getValue();
          var mposition_id = this.topToolbar.mposition_id.getValue();
          var marea_id = this.topToolbar.marea_id.getValue();
          var musername = this.topToolbar.musername.getValue();
          this.filter     ={'department_id':mdepartment_id,'position_id':mposition_id,'area_id':marea_id,'username':musername,'subject_id':subject_id,'selectType':this.filter.selectType};
        }
        this.filter.selMember=tmp_selMember;
        var condition = {'start':0,'limit':Mt.Subject.Config.PageSize};
        Ext.apply(condition,this.filter);
        ExtServiceSubject.queryPageSubjectMember(condition,function(provider, response) {
          if (response.result&&response.result.data) {
            var result       = new Array();
            result['data']     =response.result.data;
            result['totalCount'] =response.result.totalCount;
            Mt.Subject.Store.selectMemberStore.loadData(result);
          } else {
            Mt.Subject.Store.selectMemberStore.removeAll();
            Ext.Msg.alert('提示', '无符合条件的会员！');
          }
        });
      },
      /**
      * 修改查询条件
      */
      changeFilter: function(){
        var selData =Mt.Subject.View.Running.selectMemberWindow.selData;
        var selArr  = new Array();
        for(var x in selData){
          selArr.push(x);
        }
        this.filter.selMember = selArr.join(",");
      }
    }),
  },
	/**
	 * 窗口：批量上传专场
	 */
	UploadWindow:Ext.extend(Ext.Window,{
		constructor : function(config) {
			config = Ext.apply({
				title : '批量上传专场数据',width : 400,height : 110,minWidth : 300,minHeight : 100,
				layout : 'fit',plain : true,bodyStyle : 'padding:5px;',buttonAlign : 'center',closeAction : "hide",
				items : [
					new Ext.form.FormPanel({
						ref:'uploadForm',fileUpload: true,
						width: 500,labelWidth: 50,autoHeight: true,baseCls: 'x-plain',
						frame:true,bodyStyle: 'padding: 10px 10px 10px 10px;',
						defaults: {
							anchor: '95%',allowBlank: false,msgTarget: 'side'
						},
						items : [{
							xtype : 'fileuploadfield',
							fieldLabel : '文 件',name : 'upload_file',ref:'upload_file',
							emptyText: '请上传专场Excel文件',buttonText: '',
							accept:'application/vnd.ms-excel',
							buttonCfg: {iconCls: 'upload-icon'}
						}]
					})
				],
				buttons : [{
						text : '上 传',
						scope:this,
						handler : function() {
							uploadWindow       =this;
							validationExpression   =/([\u4E00-\u9FA5]|\w)+(.xlsx|.XLSX|.xls|.XLS)$/;/**允许中文名*/
							var isValidExcelFormat = new RegExp(validationExpression);
							var result       = isValidExcelFormat.test(this.uploadForm.upload_file.getValue());
							if (!result){
								Ext.Msg.alert('提示', '请上传Excel文件，后缀名为xls或者xlsx！');
								return;
							}
							if (this.uploadForm.getForm().isValid()) {
								Ext.Msg.show({
									title : '请等待',msg : '文件正在上传中，请稍后...',
									animEl : 'loading',icon : Ext.Msg.WARNING,
									closable : true,progress : true,progressText : '',width : 300
								});
								this.uploadForm.getForm().submit({
									url : 'index.php?go=admin.upload.uploadSubject',
									success : function(form, response) {
										Ext.Msg.alert('成功', '上传成功');
										uploadWindow.hide();
										uploadWindow.uploadForm.upload_file.setValue('');
										Mt.Subject.View.Running.subjectGrid.doSelectSubject();
									},
									failure : function(form, response) {
										Ext.Msg.alert('错误', response.result.data);
									}
								});
							}
						}
					},{
						text : '取 消',
						scope:this,
						handler : function() {
							this.uploadForm.upload_file.setValue('');
							this.hide();
						}
					},{
            text : '下载模版',
            scope:this,
            handler : function() {
              ExtServiceMember.template('subject',function(provider, response) {
                if (response.result) {
                  window.open(response.result);
                }
                 });
            }
          }]
				}, config);
			Mt.Subject.View.UploadWindow.superclass.constructor.call(this, config);
		}
	}),
	/**
	 * 视图：专场列表
	 */
	Grid:Ext.extend(Ext.grid.GridPanel, {
		constructor : function(config) {
			config = Ext.apply({
				/**
				 * 查询条件
				 */
				filter:null,
				region : 'center',
				store : Mt.Subject.Store.subjectStore,
				sm : this.sm,
				frame : true,trackMouseOver : true,enableColumnMove : true,columnLines : true,
				loadMask : true,stripeRows : true,headerAsText : false,
				defaults : {
					autoScroll : true
				},
				cm : new Ext.grid.ColumnModel({
					defaults:{
						width:120,sortable : true
					},
					columns : [
						this.sm,
            {header : '标识',dataIndex : 'subject_id',hidden:true},
            {header : '所属用户',dataIndex : 'admin_name'},
            {header : '专场名称',dataIndex : 'subject_name'},
            {header : '开始时间',dataIndex : 'begin_time',renderer:Ext.util.Format.dateRenderer('Y-m-d')},
            {header : '结束时间',dataIndex : 'end_time',renderer:Ext.util.Format.dateRenderer('Y-m-d')},
            {header : '排序',dataIndex : 'sort_order'},
            {header : '是否显示',dataIndex : 'isShow',renderer:function(value){if (value == true) {return "是";}else{return "否";}}}
					]
				}),
				tbar : {
					xtype : 'container',layout : 'anchor',height : 27 * 2,style:'font-size:14px',
					defaults : {
						height : 27,anchor : '100%'
					},
					items : [
						new Ext.Toolbar({
							enableOverflow: true,width : 100,
							defaults : {
								xtype : 'textfield',
								listeners : {
								   specialkey : function(field, e) {
										if (e.getKey() == Ext.EventObject.ENTER)this.ownerCt.ownerCt.ownerCt.doSelectSubject();
									}
								}
							},
							items : [
                '专场名称','&nbsp;&nbsp;',{ref: '../ssubject_name'},'&nbsp;&nbsp;',
								{
									xtype : 'button',text : '查询',scope: this,
									handler : function() {
										this.doSelectSubject();
									}
								},
								{
									xtype : 'button',text : '重置',scope: this,
									handler : function() {
                    this.topToolbar.ssubject_name.setValue("");
										this.filter={};
										this.doSelectSubject();
									}
								}]
						}),
						new Ext.Toolbar({
							defaults:{scope: this},
							items : [
								{
									text: '反选',iconCls : 'icon-reverse',
									handler: function(){
										this.onReverseSelect();
									}
								},'-',{
									text : '添加专场',iconCls : 'icon-add',
									handler : function() {
										this.addSubject();
									}
								},'-',{
									text : '修改专场',ref: '../../btnUpdate',iconCls : 'icon-edit',disabled : true,
									handler : function() {
										this.updateSubject();
									}
								},'-',{
									text : '删除专场', ref: '../../btnRemove',iconCls : 'icon-delete',disabled : true,
									handler : function() {
										this.deleteSubject();
									}
								},'-',{
									xtype:'tbsplit',text: '导入', iconCls : 'icon-import',
									handler : function() {
										this.importSubject();
									},
									menu: {
										xtype:'menu',plain:true,
										items: [
											{text:'批量导入专场',iconCls : 'icon-import',scope:this,handler:function(){this.importSubject()}}
										]}
								},'-',{
									text : '导出',iconCls : 'icon-export',
									handler : function() {
										this.exportSubject();
									}
								},'-',{
                  text : '专场报表导出',iconCls : 'icon-export',
                  handler : function() {
                    this.exportSubjectInfo();
                  }
                },'-',{
                  text : '专场学员报表导出',iconCls : 'icon-export',
                  handler : function() {
                    this.exportMember();
                  }
                },'-',{
									xtype:'tbsplit',text: '查看专场', ref:'../../tvpView',iconCls : 'icon-updown',
									enableToggle: true, disabled : true,
									handler:function(){this.showSubject()},
									menu: {
										xtype:'menu',plain:true,
										items: [
											{text:'上方',group:'mlayout',checked:false,iconCls:'view-top',scope:this,handler:function(){this.onUpDown(1)}},
											{text:'下方',group:'mlayout',checked:true ,iconCls:'view-bottom',scope:this,handler:function(){this.onUpDown(2)}},
											{text:'左侧',group:'mlayout',checked:false,iconCls:'view-left',scope:this,handler:function(){this.onUpDown(3)}},
											{text:'右侧',group:'mlayout',checked:false,iconCls:'view-right',scope:this,handler:function(){this.onUpDown(4)}},
											{text:'隐藏',group:'mlayout',checked:false,iconCls:'view-hide',scope:this,handler:function(){this.hideSubject();Mt.Subject.Config.View.IsShow=0;}},'-',
											{text: '固定',ref:'mBind',checked: true,scope:this,checkHandler:function(item, checked){this.onBindGrid(item, checked);Mt.Subject.Cookie.set('View.IsFix',Mt.Subject.Config.View.IsFix);}}
										]}
								},'-',{
                  text : '选择课程',ref:'../../tlesson',iconCls : 'icon-edit',disabled : true,
                  handler : function() {
                    if(Mt.Subject.View.Running.selectLessonWindow==null || Mt.Subject.View.Running.selectLessonWindow.hidden){
                      this.showLesson();
                    }else{
                      this.hideLesson();
                    }
                  }
                },'-',{
                  text : '选择会员',ref:'../../tmember',iconCls : 'icon-edit',disabled : true,
                  handler : function() {
                    if(Mt.Subject.View.Running.selectMemberWindow==null || Mt.Subject.View.Running.selectMemberWindow.hidden){
                      this.showMember();
                    }else{
                      this.hideMember();
                    }
                  }
                },'-']}
					)]
				},
				bbar: new Ext.PagingToolbar({
					pageSize: Mt.Subject.Config.PageSize,
					store: Mt.Subject.Store.subjectStore,
					scope:this,autoShow:true,displayInfo: true,
					displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',
					emptyMsg: "无显示数据",
					listeners:{
						change:function(thisbar,pagedata){
							if (Mt.Subject.Viewport){
								if (Mt.Subject.Config.View.IsShow==1){
									Mt.Subject.View.IsSelectView=1;
								}
								this.ownerCt.hideSubject();
								Mt.Subject.Config.View.IsShow=0;
							}
						}
					},
					items: [
						{xtype:'label', text: '每页显示'},
						{xtype:'numberfield', value:Mt.Subject.Config.PageSize,minValue:1,width:35,
							style:'text-align:center',allowBlank: false,
							listeners:
							{
								change:function(Field, newValue, oldValue){
									var num = parseInt(newValue);
									if (isNaN(num) || !num || num<1)
									{
										num = Mt.Subject.Config.PageSize;
										Field.setValue(num);
									}
									this.ownerCt.pageSize= num;
									Mt.Subject.Config.PageSize = num;
									this.ownerCt.ownerCt.doSelectSubject();
								},
								specialKey :function(field,e){
									if (e.getKey() == Ext.EventObject.ENTER){
										var num = parseInt(field.getValue());
										if (isNaN(num) || !num || num<1)
										{
											num = Mt.Subject.Config.PageSize;
										}
										this.ownerCt.pageSize= num;
										Mt.Subject.Config.PageSize = num;
										this.ownerCt.ownerCt.doSelectSubject();
									}
								}
							}
						},
						{xtype:'label', text: '个'}
					]
				})
			}, config);
			//初始化显示专场列表
			this.doSelectSubject();
			Mt.Subject.View.Grid.superclass.constructor.call(this, config);
			//创建在Grid里显示的专场信息Tab页
			Mt.Subject.View.Running.viewTabs=new Mt.Subject.View.SubjectView.Tabs();
			this.addListener('rowdblclick', this.onRowDoubleClick);
		},
		/**
		 * 行选择器
		 */
		sm : new Ext.grid.CheckboxSelectionModel({
			//handleMouseDown : Ext.emptyFn,
			listeners : {
				selectionchange:function(sm) {
					// 判断删除和更新按钮是否可以激活
					this.grid.btnRemove.setDisabled(sm.getCount() < 1);
					this.grid.btnUpdate.setDisabled(sm.getCount() != 1);
					this.grid.tvpView.setDisabled(sm.getCount() != 1);
          this.grid.tlesson.setDisabled(sm.getCount() != 1);
          this.grid.tmember.setDisabled(sm.getCount() != 1);
				},
				rowselect: function(sm, rowIndex, record) {
					if (sm.getCount() != 1){
						this.grid.hideSubject();
						Mt.Subject.Config.View.IsShow=0;
            this.grid.hideLesson();
            this.grid.hideMember();
					}else{
						if (Mt.Subject.View.IsSelectView==1){
							Mt.Subject.View.IsSelectView=0;
							this.grid.showSubject();
						}
					}
				},
				rowdeselect: function(sm, rowIndex, record) {
					if (sm.getCount() != 1){
						if (Mt.Subject.Config.View.IsShow==1){
							Mt.Subject.View.IsSelectView=1;
						}
						this.grid.hideSubject();
						Mt.Subject.Config.View.IsShow=0;
					}
				}
			}
		}),
		/**
		 * 双击选行
		 */
		onRowDoubleClick:function(grid, rowIndex, e){
			if (!Mt.Subject.Config.View.IsShow){
				this.sm.selectRow(rowIndex);
				this.showSubject();
				this.tvpView.toggle(true);
			}else{
				this.hideSubject();
				Mt.Subject.Config.View.IsShow=0;
				this.sm.deselectRow(rowIndex);
				this.tvpView.toggle(false);
			}
		},
		/**
		 * 是否绑定在本窗口上
		 */
		onBindGrid:function(item, checked){
			if (checked){
			   Mt.Subject.Config.View.IsFix=1;
			}else{
			   Mt.Subject.Config.View.IsFix=0;
			}
			if (this.getSelectionModel().getSelected()==null){
				Mt.Subject.Config.View.IsShow=0;
				return ;
			}
			if (Mt.Subject.Config.View.IsShow==1){
			   this.hideSubject();
			   Mt.Subject.Config.View.IsShow=0;
			}
			this.showSubject();
		},
		/**
		 * 反选
		 */
		onReverseSelect:function() {
			for (var i = this.getView().getRows().length - 1; i >= 0; i--) {
				if (this.sm.isSelected(i)) {
					this.sm.deselectRow(i);
				}else {
					this.sm.selectRow(i, true);
				}
			}
		},
		/**
		 * 查询符合条件的专场
		 */
		doSelectSubject : function() {
			if (this.topToolbar){
        var ssubject_name = this.topToolbar.ssubject_name.getValue();
        this.filter     ={'subject_name':ssubject_name};
			}
			var condition = {'start':0,'limit':Mt.Subject.Config.PageSize};
			Ext.apply(condition,this.filter);
			ExtServiceSubject.queryPageSubject(condition,function(provider, response) {
				if (response.result&&response.result.data) {
					var result       = new Array();
					result['data']     =response.result.data;
					result['totalCount'] =response.result.totalCount;
					Mt.Subject.Store.subjectStore.loadData(result);
				} else {
					Mt.Subject.Store.subjectStore.removeAll();
					Ext.Msg.alert('提示', '无符合条件的专场！');
				}
			});
		},
		/**
		 * 显示专场视图
		 * 显示专场的视图相对专场列表Grid的位置
		 * 1:上方,2:下方,0:隐藏。
		 */
		onUpDown:function(viewDirection){
			Mt.Subject.Config.View.Direction=viewDirection;
			switch(viewDirection){
				case 1:
					this.ownerCt.north.add(Mt.Subject.View.Running.viewTabs);
					break;
				case 2:
					this.ownerCt.south.add(Mt.Subject.View.Running.viewTabs);
					break;
				case 3:
					this.ownerCt.west.add(Mt.Subject.View.Running.viewTabs);
					break;
				case 4:
					this.ownerCt.east.add(Mt.Subject.View.Running.viewTabs);
					break;
			}
			Mt.Subject.Cookie.set('View.Direction',Mt.Subject.Config.View.Direction);
			if (this.getSelectionModel().getSelected()!=null){
				if ((Mt.Subject.Config.View.IsFix==0)&&(Mt.Subject.Config.View.IsShow==1)){
					this.showSubject();
				}
				Mt.Subject.Config.View.IsFix=1;
				Mt.Subject.View.Running.subjectGrid.tvpView.menu.mBind.setChecked(true,true);
				Mt.Subject.Config.View.IsShow=0;
				this.showSubject();
			}
		},
		/**
		 * 显示专场
		 */
		showSubject : function(){
			if (this.getSelectionModel().getSelected()==null){
				Ext.Msg.alert('提示', '请先选择专场！');
				Mt.Subject.Config.View.IsShow=0;
				this.tvpView.toggle(false);
				return ;
			}
			if (Mt.Subject.Config.View.IsFix==0){
				if (Mt.Subject.View.Running.view_window==null){
					Mt.Subject.View.Running.view_window=new Mt.Subject.View.SubjectView.Window();
				}
				if (Mt.Subject.View.Running.view_window.hidden){
					Mt.Subject.View.Running.view_window.show();
					Mt.Subject.View.Running.view_window.winTabs.hideTabStripItem(Mt.Subject.View.Running.view_window.winTabs.tabFix);
					this.updateViewSubject();
					this.tvpView.toggle(true);
					Mt.Subject.Config.View.IsShow=1;
				}else{
					this.hideSubject();
					Mt.Subject.Config.View.IsShow=0;
				}
				return;
			}
			switch(Mt.Subject.Config.View.Direction){
				case 1:
					if (!this.ownerCt.north.items.contains(Mt.Subject.View.Running.viewTabs)){
						this.ownerCt.north.add(Mt.Subject.View.Running.viewTabs);
					}
					break;
				case 2:
					if (!this.ownerCt.south.items.contains(Mt.Subject.View.Running.viewTabs)){
						this.ownerCt.south.add(Mt.Subject.View.Running.viewTabs);
					}
					break;
				case 3:
					if (!this.ownerCt.west.items.contains(Mt.Subject.View.Running.viewTabs)){
						this.ownerCt.west.add(Mt.Subject.View.Running.viewTabs);
					}
					break;
				case 4:
					if (!this.ownerCt.east.items.contains(Mt.Subject.View.Running.viewTabs)){
						this.ownerCt.east.add(Mt.Subject.View.Running.viewTabs);
					}
					break;
			}
			this.hideSubject();
			if (Mt.Subject.Config.View.IsShow==0){
				Mt.Subject.View.Running.viewTabs.enableCollapse();
				switch(Mt.Subject.Config.View.Direction){
					case 1:
						this.ownerCt.north.show();
						break;
					case 2:
						this.ownerCt.south.show();
						break;
					case 3:
						this.ownerCt.west.show();
						break;
					case 4:
						this.ownerCt.east.show();
						break;
				}
				this.updateViewSubject();
				this.tvpView.toggle(true);
				Mt.Subject.Config.View.IsShow=1;
			}else{
				Mt.Subject.Config.View.IsShow=0;
			}
			this.ownerCt.doLayout();
		},
		/**
		 * 隐藏专场
		 */
		hideSubject : function(){
			this.ownerCt.north.hide();
			this.ownerCt.south.hide();
			this.ownerCt.west.hide();
			this.ownerCt.east.hide();
			if (Mt.Subject.View.Running.view_window!=null){
				Mt.Subject.View.Running.view_window.hide();
			}
			this.tvpView.toggle(false);
			this.ownerCt.doLayout();
		},
		/**
		 * 更新当前专场显示信息
		 */
		updateViewSubject : function() {
      Mt.Subject.View.Running.slessonGrid.doSelectSlesson();
			if (Mt.Subject.View.Running.view_window!=null){
				Mt.Subject.View.Running.view_window.winTabs.tabSubjectDetail.update(this.getSelectionModel().getSelected().data);
			}
			Mt.Subject.View.Running.viewTabs.tabSubjectDetail.update(this.getSelectionModel().getSelected().data);
		},
		/**
		 * 新建专场
		 */
		addSubject : function() {
			if (Mt.Subject.View.Running.edit_window==null){
				Mt.Subject.View.Running.edit_window=new Mt.Subject.View.EditWindow();
			}
			Mt.Subject.View.Running.edit_window.resetBtn.setVisible(false);
			Mt.Subject.View.Running.edit_window.saveBtn.setText('保 存');
			Mt.Subject.View.Running.edit_window.setTitle('添加专场');
			Mt.Subject.View.Running.edit_window.savetype=0;
			Mt.Subject.View.Running.edit_window.subject_id.setValue("");
      Mt.Subject.View.Running.edit_window.head_imageUpload.setValue("");
			Mt.Subject.View.Running.edit_window.show();
			Mt.Subject.View.Running.edit_window.maximize();
		},
		/**
		 * 编辑专场时先获得选中的专场信息
		 */
		updateSubject : function() {
			if (Mt.Subject.View.Running.edit_window==null){
				Mt.Subject.View.Running.edit_window=new Mt.Subject.View.EditWindow();
			}
			Mt.Subject.View.Running.edit_window.saveBtn.setText('修 改');
			Mt.Subject.View.Running.edit_window.resetBtn.setVisible(true);
			Mt.Subject.View.Running.edit_window.setTitle('修改专场');
			Mt.Subject.View.Running.edit_window.editForm.form.loadRecord(this.getSelectionModel().getSelected());
			Mt.Subject.View.Running.edit_window.savetype=1;
      Mt.Subject.View.Running.edit_window.head_imageUpload.setValue(Mt.Subject.View.Running.edit_window.head_image.getValue());
			Mt.Subject.View.Running.edit_window.show();
			Mt.Subject.View.Running.edit_window.maximize();
		},
		/**
		 * 删除专场
		 */
		deleteSubject : function() {
			Ext.Msg.confirm('提示', '确实要删除所选的专场吗?', this.confirmDeleteSubject,this);
		},
		/**
		 * 确认删除专场
		 */
		confirmDeleteSubject : function(btn) {
			if (btn == 'yes') {
				var del_subject_ids ="";
				var selectedRows  = this.getSelectionModel().getSelections();
				for ( var flag = 0; flag < selectedRows.length; flag++) {
					del_subject_ids=del_subject_ids+selectedRows[flag].data.subject_id+",";
				}
				ExtServiceSubject.deleteByIds(del_subject_ids);
				this.doSelectSubject();
				Ext.Msg.alert("提示", "删除成功！");
			}
		},
    /**
     * 显示课程
     */
    showLesson:function(){
      if (Mt.Subject.View.Running.selectLessonWindow==null){
        Mt.Subject.View.Running.selectLessonWindow=new Mt.Subject.View.LessonView.SelectLessonWindow();
      }
      var subject_id=Mt.Subject.View.Running.subjectGrid.getSelectionModel().getSelected().data.subject_id;

      //关联课程ID组成的字符串
      var lessonStr  = Mt.Subject.View.Running.subjectGrid.getSelectionModel().getSelected().data.lessonStr;
      var selData  = {};
      var oldData  = {};
      if(lessonStr){
        var lessonArr = lessonStr.split(",");
        for(var i=0;i<lessonArr.length;i++){
          selData[lessonArr[i]] = true;//ture为已存在的关联货品
          oldData[lessonArr[i]] = {};
          oldData[lessonArr[i]].active = true;
        }
      }
      var selLessonWin   = Mt.Subject.View.Running.selectLessonWindow;
      var selLessonGrid  = selLessonWin.lessonGrid;
      selLessonWin.selData = selData;
      selLessonWin.oldData = oldData;
      selLessonWin.changeTitle();//根据选择的货品,修改标题

      selLessonGrid.subject_id = subject_id;
      if (selLessonWin.hidden){
        Mt.Subject.View.Running.selectLessonWindow.lessonGrid.topToolbar.llesson_name.setValue("");
        selLessonGrid.filter = {selLesson:lessonStr};
        selLessonGrid.topToolbar.menus.all.setChecked(true);
        selLessonGrid.isSelect.toggle(false);
        Mt.Subject.Store.selectLessonStore.removeAll();
      }
      selLessonGrid.doSelectLesson();
      selLessonWin.show();
    },
    /**
     * 隐藏课程
     */
    hideLesson:function(){
      if (Mt.Subject.View.Running.selectLessonWindow!=null){
        Mt.Subject.View.Running.selectLessonWindow.hide();
      }
    },
    /**
     * 显示会员
     */
    showMember:function(){
      if (Mt.Subject.View.Running.selectMemberWindow==null){
        Mt.Subject.View.Running.selectMemberWindow=new Mt.Subject.View.MemberView.SelectMemberWindow();
      }
      var subject_id=Mt.Subject.View.Running.subjectGrid.getSelectionModel().getSelected().data.subject_id;

      //关联会员ID组成的字符串
      var memberStr  = Mt.Subject.View.Running.subjectGrid.getSelectionModel().getSelected().data.memberStr;
      var selData  = {};
      var oldData  = {};
      if(memberStr){
        var memberArr = memberStr.split(",");
        for(var i=0;i<memberArr.length;i++){
          selData[memberArr[i]] = true;//ture为已存在的关联货品
          oldData[memberArr[i]] = {};
          oldData[memberArr[i]].active = true;
        }
      }
      var selMemberWin   = Mt.Subject.View.Running.selectMemberWindow;
      var selMemberGrid  = selMemberWin.memberGrid;
      selMemberWin.selData = selData;
      selMemberWin.oldData = oldData;
      selMemberWin.changeTitle();//根据选择的货品,修改标题

      selMemberGrid.subject_id = subject_id;
      if (selMemberWin.hidden){
        // Mt.Subject.View.Running.selectMemberWindow.memberGrid.topToolbar.mcompany_id.setValue("");
        Mt.Subject.View.Running.selectMemberWindow.memberGrid.topToolbar.mdepartment_id.setValue("");
        Mt.Subject.View.Running.selectMemberWindow.memberGrid.topToolbar.mposition_id.setValue("");
        Mt.Subject.View.Running.selectMemberWindow.memberGrid.topToolbar.marea_id.setValue("");
        Mt.Subject.View.Running.selectMemberWindow.memberGrid.topToolbar.musername.setValue("");
        selMemberGrid.filter = {selMember:memberStr};
        selMemberGrid.topToolbar.menus.all.setChecked(true);
        selMemberGrid.isSelect.toggle(false);
        Mt.Subject.Store.selectMemberStore.removeAll();
      }
      selMemberGrid.doSelectMember();
      selMemberWin.show();
    },
    /**
     * 隐藏会员
     */
    hideMember:function(){
      if (Mt.Subject.View.Running.selectMemberWindow!=null){
        Mt.Subject.View.Running.selectMemberWindow.hide();
      }
    },
		/**
		 * 导出专场
		 */
		exportSubject : function() {
			ExtServiceSubject.exportSubject(this.filter,function(provider, response) {
				if (response.result.data) {
					window.open(response.result.data);
				}
			});
		},
    /**
     * 导出专场报表
     */
    exportSubjectInfo : function() {
      ExtServiceSubject.exportSubjectInfo(this.filter,function(provider, response) {
        if (response.result.data) {
          window.open(response.result.data);
        }
      });
    },
    /**
     * 导出专场学员报表
     */
    exportMember : function() {
      ExtServiceSubject.exportMember(this.filter,function(provider, response) {
        if (response.result.data) {
          window.open(response.result.data);
        }
      });
    },
		/**
		 * 导入专场
		 */
		importSubject : function() {
			if (Mt.Subject.View.current_uploadWindow==null){
				Mt.Subject.View.current_uploadWindow=new Mt.Subject.View.UploadWindow();
			}
			Mt.Subject.View.current_uploadWindow.show();
		}
	}),
	/**
	 * 核心内容区
	 */
	Panel:Ext.extend(Ext.form.FormPanel,{
		constructor : function(config) {
			Mt.Subject.View.Running.subjectGrid=new Mt.Subject.View.Grid();
			if (Mt.Subject.Config.View.IsFix==0){
				Mt.Subject.View.Running.subjectGrid.tvpView.menu.mBind.setChecked(false,true);
			}
			config = Ext.apply({
				region : 'center',layout : 'fit', frame:true,
				items: {
					layout:'border',
					items:[
						Mt.Subject.View.Running.subjectGrid,
						{region:'north',ref:'north',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true},
						{region:'south',ref:'south',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true,items:[Mt.Subject.View.Running.viewTabs]},
						{region:'west',ref:'west',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true},
						{region:'east',ref:'east',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true}
					]
				}
			}, config);
			Mt.Subject.View.Panel.superclass.constructor.call(this, config);
		}
	}),
	/**
	 * 当前运行的可视化对象
	 */
	Running:{
		/**
		 * 当前专场Grid对象
		 */
		subjectGrid:null,
    /**
     * 当前专场课程Grid对象
     */
    slessonGrid:null,
    /**
     * 推荐课程
     */
    selectLessonWindow:null,
    /**
     * 推荐会员
     */
    selectMemberWindow:null,
		/**
		 * 显示专场信息及关联信息列表的Tab页
		 */
		viewTabs:null,
		/**
		 * 当前创建的编辑窗口
		 */
		edit_window:null,
		/**
		 * 当前的显示窗口
		 */
		view_window:null
	}
};
/**
 * Controller:主程序
 */
Ext.onReady(function(){
	Ext.QuickTips.init();
	Ext.state.Manager.setProvider(Mt.Subject.Cookie);
	Ext.Direct.addProvider(Ext.app.REMOTING_API);
	Mt.Subject.Init();
	/**
	 * 专场数据模型获取数据Direct调用
	 */
	Mt.Subject.Store.subjectStore.proxy=new Ext.data.DirectProxy({
		api: {read:ExtServiceSubject.queryPageSubject}
	});
	/**
	 * 专场页面布局
	 */
	Mt.Subject.Viewport = new Ext.Viewport({
		layout : 'border',
		items : [new Mt.Subject.View.Panel()]
	});
	Mt.Subject.Viewport.doLayout();
	setTimeout(function(){
		Ext.get('loading').remove();
		Ext.get('loading-mask').fadeOut({
			remove:true
		});
	}, 250);
});